﻿using Chloe.Infrastructure.Interception;
using Chloe.SqlServer;
using System;
using System.Configuration;

namespace XXZPrint.Models.DataOperation
{
    public class C_DbContext : IDisposable
    {
        private MsSqlContext aDbContext = null;

        private string aConnectionStrings;

        public C_DbContext()
        {
            aConnectionStrings = ConfigurationManager.ConnectionStrings["MainCon"].ConnectionString;
        }

        public C_DbContext(string ConnName)
        {
            if (ConfigurationManager.ConnectionStrings[ConnName] == null)
            {
                aConnectionStrings = ConfigurationManager.ConnectionStrings["MainCon"].ConnectionString;
            }
            else
            {
                aConnectionStrings = ConfigurationManager.ConnectionStrings[ConnName].ConnectionString;
            }
        }

        /// <summary>
        /// 返回连接对象
        /// </summary>
        public MsSqlContext DbContext
        {
            get { return GetDbContext(); }
        }

        public MsSqlContext GetDbContext()
        {
            if (aDbContext == null)
            {
                aDbContext = new MsSqlContext(aConnectionStrings);
                IDbCommandInterceptor interceptor = new C_DbCommandInterceptor();
                aDbContext.Session.AddInterceptor(interceptor);
            }

            return aDbContext;
        }

        void IDisposable.Dispose()
        {
            if (aDbContext != null)
            {
                aDbContext.Dispose();
            }
        }
    }
}